package com.sky.service.impl;

import com.atom.module.common.result.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.common.constant.MessageConstant;
import com.sky.common.constant.StatusConstant;
import com.sky.common.exception.DeletionNotAllowedException;
import com.sky.common.exception.SetmealEnableFailedException;
import com.sky.pojo.dto.SetMealDTO;
import com.sky.pojo.dto.SetMealDishDTO;
import com.sky.pojo.dto.SetMealPageQueryDTO;
import com.sky.pojo.entity.Dish;
import com.sky.pojo.entity.SetMeal;
import com.sky.pojo.entity.SetMealDish;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.service.SetMealService;
import com.sky.pojo.vo.DishItemVO;
import com.sky.pojo.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Function;

@Slf4j
@Service
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealMapper setmealMapper;

    @Autowired
    private SetMealDishMapper setmealDishMapper;

    @Autowired
    private DishMapper dishMapper;

    @Transactional
    @Override
    public void save(SetMealDTO setmealDTO) {

        // 进行插入 TODO  根据分类id查询是否存在对应的分类/检查是否存在对应的菜品/ 检查无误后方可插入
        SetMeal setmeal = new SetMeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmeal.setStatus(StatusConstant.DISABLE);
        setmealMapper.insert(setmeal);
        log.info("setmealId: {}", setmeal.getId());

        //2.构造套餐菜品信息，保存数据到套餐菜品关系表setmeal_dish中
        List<SetMealDishDTO> setMealDishes = setmealDTO.getSetMealDishes();
        List<SetMealDish> list = setMealDishes.stream().map(new Function<SetMealDishDTO, SetMealDish>() {
            @Override
            public SetMealDish apply(SetMealDishDTO setMealDishDTO) {
                SetMealDish setMealDish = new SetMealDish();
                BeanUtils.copyProperties(setMealDishDTO, setMealDish);
                setMealDish.setSetmealId(setmeal.getId());
                return setMealDish;
            }
        }).toList();
        setmealDishMapper.insertBatch(list);
    }

    @Override
    public PageResult pageQuery(SetMealPageQueryDTO setmealPageQueryDTO) {
        int pageNum = setmealPageQueryDTO.getPage();
        int pageSize = setmealPageQueryDTO.getPageSize();

        PageHelper.startPage(pageNum, pageSize);

        Page<SetmealVO> page = setmealMapper.pageQuery(setmealPageQueryDTO);
        return new PageResult(page.getResult(), page.getTotal());
    }

    @Transactional
    @Override
    public void delete(List<Long> ids) {
        //1.起售中的套餐不能删除
        ids.forEach(id -> {
            SetMeal setmeal = setmealMapper.selectById(id);
            if (setmeal.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        });

        //2.删除套餐的同时，需要将套餐菜品关系数据删除
        ids.forEach(setmealId -> {
            //删除套餐表中的数据
            setmealMapper.deleteById(setmealId);
            //删除套餐菜品关系表中的数据
            setmealDishMapper.deleteBySetmealId(setmealId);
        });

    }

    @Override
    public SetmealVO getByIdWithDish(Long id) {
        return setmealMapper.getByIdWithDish(id);
    }

    @Transactional
    @Override
    public void update(SetMealDTO setmealDTO) {
        SetMeal setmeal = new SetMeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        //1、修改套餐表，执行update
        setmealMapper.update(setmeal);

        //套餐id
        Long setmealId = setmealDTO.getId();

        //2、删除套餐和菜品的关联关系，操作setmeal_dish表，执行delete
        setmealDishMapper.deleteBySetmealId(setmealId);

        List<SetMealDish> list = setmealDTO.getSetMealDishes().stream().map(new Function<SetMealDishDTO, SetMealDish>() {
            @Override
            public SetMealDish apply(SetMealDishDTO setMealDishDTO) {
                SetMealDish setMealDish = new SetMealDish();
                BeanUtils.copyProperties(setMealDishDTO, setMealDish);
                setMealDish.setSetmealId(setmeal.getId());
                return setMealDish;
            }
        }).toList();
        setmealDishMapper.insertBatch(list);
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        //起售套餐时，判断套餐内是否有停售菜品，有停售菜品提示"套餐内包含未启售菜品，无法启售"
        if (status.equals(StatusConstant.ENABLE)) {
            //select a.* from dish a left join setmeal_dish b on a.id = b.dish_id where b.setmeal_id = ?
            List<Dish> dishList = dishMapper.getBySetmealId(id);
            if (!dishList.isEmpty()) {
                dishList.forEach(dish -> {
                    if (StatusConstant.DISABLE.equals(dish.getStatus())) {
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }

        SetMeal setmeal = SetMeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.update(setmeal);
    }

    @Override
    public List<SetMeal> list(SetMeal setmeal) {
        return setmealMapper.list(setmeal);
    }

    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
}
